package hotnet.session;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultIoSessionAttributeMap implements IoSessionAttributeMap {
	public static String CONNECT_FUTURE = "connect_future";
	
	private final ConcurrentHashMap<Object, Object> attributes = new ConcurrentHashMap<Object, Object>();
	
	private void checkKeyNotNull(Object key) {
		if (key == null) {
            throw new IllegalArgumentException("key");
        }
	}
	
	public Object getAttribute(Object key, Object defaultValue) {
		checkKeyNotNull(key);
		
		if (defaultValue == null) {
			return attributes.get(key);
		}
		
		Object object = attributes.putIfAbsent(key, defaultValue);
		
		if (object != null) {
			return object;
		} else {
			return defaultValue;
		}
	}
	
	public Object setAttribute(Object key, Object value) {
		checkKeyNotNull(key);
		
		if (value == null)
			return null;
		
		return attributes.put(key, value);
	}
	
	public Object setAttributeIfAbsent(Object key, Object value) {
		checkKeyNotNull(key);
		
		if (value == null)
			return null;
		
		return attributes.putIfAbsent(key, value);
	}
	
	public Object removeAttribute(Object key) {
		checkKeyNotNull(key);
		
		return attributes.remove(key);
	}
	
	public boolean removeAttribute(Object key, Object value) {
		checkKeyNotNull(key);
		
		if (value == null)
			return false;
		
		return attributes.remove(key, value);
	}
	
	public boolean replaceAttribute(Object key, Object oldValue, Object newValue) {
		checkKeyNotNull(key);
		
		if (oldValue == null || newValue == null)
			return false;
		
		return attributes.replace(key, oldValue, newValue);
	}
	
	public boolean containsAttribute(Object key) {
		if (key == null) {
			return false;
		}
		
		return attributes.containsKey(key);
	}
	
	public Set<Object> getAttributeKeys() {
		return new HashSet<Object>(attributes.keySet());
	}
}
